-module( erlServe_book_controller, [Req]).

-compile(export_all).

-default_action('list').

list('GET', [] ) ->
	Books = boss_db:find(book, []),
	{ok, [{books, Books}]}.

view('GET', [BookId]) ->
	Book = boss_db:find(BookId),
	{ok, [{book, Book}]}.

edit('GET', [BookId]) ->
	Book = boss_db:find(BookId),
	{ok, [{book, Book}]};

edit('POST', [BookId]) ->
	Book = boss_db:find(BookId),
	Book:title( Req:post_param("title") ),
	Book:author_name( Req:post_param("author_name") ),

	case boss_db:save_record(Book) of
		{ok, SavedBook} ->
				{redirect, "/book/view/"++BookId};
	    {error, Errors} ->
			{ok, [{errors, Errors}, {book, Book}]}
	end.

add('GET', []) ->
	{ok, [] };
	
add('POST', []) ->
	Book = book:new(
		id, 
		Req:post_param("title"), 
		Req:post_param("author_name") 
	),
	case Book:save() of
		{ok, SavedBook} -> 
				{redirect, "/book/view/"++SavedBook:id()};
		{error, Errors} ->
			{ok, [{errors, Errors}, {book, Book}]}
	end.
	
delete('GET', [BookId] ) ->
	case boss_db:delete(BookId) of
		ok ->
			{redirect, "/book/list"};
		{ error, Reason} ->
			{ok, [{errors, Reason}]}
	end.
